﻿/***************************************************************
 * Name:      cloudown_main.cpp
 * Purpose:   应用程序框架类
 * Author:    杨卓荦 (yzl@bang5.net)
 * Created:   2010-08-29
 * Copyright: 杨卓荦 (http://www.bang5.net)
 * License:
 **************************************************************/

#include "cloudown_main.h"
#include <wx/msgdlg.h>
#include <string>
using namespace std;

//(*InternalHeaders(ClouDownFrame)
#include <wx/artprov.h>
#include <wx/bitmap.h>
#include <wx/icon.h>
#include <wx/intl.h>
#include <wx/image.h>
#include <wx/string.h>
//*)

// 自定义头
#include "new_task_dialog.h"  // 新建任务对话框

//helper functions
enum wxbuildinfoformat {
  short_f, long_f
};

wxString wxbuildinfo(wxbuildinfoformat format) {
  wxString wxbuild(wxVERSION_STRING);

  if (format == long_f) {
#if defined(__WXMSW__)
    wxbuild << _T("-Windows");
#elif defined(__UNIX__)
    wxbuild << _T("-Linux");
#endif

#if wxUSE_UNICODE
    wxbuild << _T("-Unicode build");
#else
    wxbuild << _T("-ANSI build");
#endif // wxUSE_UNICODE
  }

  return wxbuild;
}

//(*IdInit(ClouDownFrame)
const long ClouDownFrame::kIdTreeCtrlLeft = wxNewId();
const long ClouDownFrame::kIdListCtrlDownloading = wxNewId();
const long ClouDownFrame::kIdTextCtrlInfo = wxNewId();
const long ClouDownFrame::kIdSplitterWindowRight = wxNewId();
const long ClouDownFrame::kIdSplitterWindowMain = wxNewId();
const long ClouDownFrame::kIdMenuQuit = wxNewId();
const long ClouDownFrame::kIdMenuAbout = wxNewId();
const long ClouDownFrame::kIdStatusBarMain = wxNewId();
const long ClouDownFrame::kIdNewTask = wxNewId();
const long ClouDownFrame::kIdToolBarMain = wxNewId();
const long ClouDownFrame::kIdTimer = wxNewId();
//*)

BEGIN_EVENT_TABLE(ClouDownFrame, wxFrame)
  //(*EventTable(ClouDownFrame)
  //*)
END_EVENT_TABLE()

ClouDownFrame::ClouDownFrame(wxWindow* parent, wxWindowID id) {
  //(*Initialize(ClouDownFrame)
  wxMenuItem* menu_item_about;
  wxMenu* menu_item_file;
  wxMenu* menu_item_help;
  wxMenuItem* menu_item_quit;
  wxMenuBar* menu_bar;

  Create(parent, id, _("卓荦下载"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE, _T("id"));
  SetClientSize(wxSize(800,600));
  {
  	wxIcon FrameIcon;
  	FrameIcon.CopyFromBitmap(wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_EXECUTABLE_FILE")),wxART_FRAME_ICON));
  	SetIcon(FrameIcon);
  }
  splitterwindow_main = new wxSplitterWindow(this, kIdSplitterWindowMain, wxDefaultPosition, wxDefaultSize, wxSP_3D, _T("kIdSplitterWindowMain"));
  splitterwindow_main->SetMinSize(wxSize(150,150));
  splitterwindow_main->SetMinimumPaneSize(150);
  treectrl_left = new wxTreeCtrl(splitterwindow_main, kIdTreeCtrlLeft, wxDefaultPosition, wxDefaultSize, wxTR_DEFAULT_STYLE, wxDefaultValidator, _T("kIdTreeCtrlLeft"));
  splitterwindow_right = new wxSplitterWindow(splitterwindow_main, kIdSplitterWindowRight, wxDefaultPosition, wxDefaultSize, wxSP_3D, _T("kIdSplitterWindowRight"));
  splitterwindow_right->SetMinSize(wxSize(150,150));
  splitterwindow_right->SetMinimumPaneSize(300);
  list_ctrl_downloading = new wxListCtrl(splitterwindow_right, kIdListCtrlDownloading, wxDefaultPosition, wxDefaultSize, wxLC_REPORT, wxDefaultValidator, _T("kIdListCtrlDownloading"));
  list_ctrl_downloading->InsertColumn(0, _("状态"));
  list_ctrl_downloading->InsertColumn(1, _("文件名称"), wxLIST_FORMAT_LEFT, 150);
  list_ctrl_downloading->InsertColumn(2, _("文件大小"), wxLIST_FORMAT_LEFT, 100);
  list_ctrl_downloading->InsertColumn(3, _("进度"));
  list_ctrl_downloading->InsertColumn(4, _("速度"));
  list_ctrl_downloading->InsertColumn(5, _("资源"));
  list_ctrl_downloading->InsertColumn(6, _("剩余时间"));
  list_ctrl_downloading->InsertColumn(7, _("用时"));
  list_ctrl_downloading->InsertColumn(8, _("文件类型"));
  text_ctrl_info = new wxTextCtrl(splitterwindow_right, kIdTextCtrlInfo, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY, wxDefaultValidator, _T("kIdTextCtrlInfo"));
  splitterwindow_right->SplitHorizontally(list_ctrl_downloading, text_ctrl_info);
  splitterwindow_right->SetSashPosition(300);
  splitterwindow_main->SplitVertically(treectrl_left, splitterwindow_right);
  splitterwindow_main->SetSashPosition(150);
  menu_bar = new wxMenuBar();
  menu_item_file = new wxMenu();
  menu_item_quit = new wxMenuItem(menu_item_file, kIdMenuQuit, _("退出(&Q)\tAlt-F4"), _("Quit the application"), wxITEM_NORMAL);
  menu_item_file->Append(menu_item_quit);
  menu_bar->Append(menu_item_file, _("文件(&F)"));
  menu_item_help = new wxMenu();
  menu_item_about = new wxMenuItem(menu_item_help, kIdMenuAbout, _("关于(&A)\tF1"), _("Show info about this application"), wxITEM_NORMAL);
  menu_item_help->Append(menu_item_about);
  menu_bar->Append(menu_item_help, _("帮助(&H)"));
  SetMenuBar(menu_bar);
  status_bar = new wxStatusBar(this, kIdStatusBarMain, 0, _T("kIdStatusBarMain"));
  int __wxStatusBarWidths_1[1] = { -1 };
  int __wxStatusBarStyles_1[1] = { wxSB_NORMAL };
  status_bar->SetFieldsCount(1,__wxStatusBarWidths_1);
  status_bar->SetStatusStyles(1,__wxStatusBarStyles_1);
  SetStatusBar(status_bar);
  tool_bar = new wxToolBar(this, kIdToolBarMain, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL|wxNO_BORDER, _T("kIdToolBarMain"));
  toolbar_item_new_task = tool_bar->AddTool(kIdNewTask, _("新建任务"), wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_NEW")),wxART_TOOLBAR), wxNullBitmap, wxITEM_NORMAL, _("新建一个下载任务"), wxEmptyString);
  tool_bar->Realize();
  SetToolBar(tool_bar);
  timer.SetOwner(this, kIdTimer);
  timer.Start(1000, false);

  Connect(kIdMenuQuit,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&ClouDownFrame::OnQuit);
  Connect(kIdMenuAbout,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&ClouDownFrame::OnAbout);
  Connect(kIdNewTask,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&ClouDownFrame::OnToolbarItemNewTaskClicked);
  Connect(kIdTimer,wxEVT_TIMER,(wxObjectEventFunction)&ClouDownFrame::OnTimerTrigger);
  //*)
}

ClouDownFrame::~ClouDownFrame() {
  //(*Destroy(ClouDownFrame)
  //*)
}

void ClouDownFrame::OnQuit(wxCommandEvent& event) {
  Close();
}

void ClouDownFrame::OnAbout(wxCommandEvent& event) {
  wxString msg = wxbuildinfo(long_f);
  wxMessageBox(msg, _("欢迎使用"));
}

void ClouDownFrame::OnToolbarItemNewTaskClicked(wxCommandEvent& event) {
  NewTaskDialog new_task_dialog(this);
  new_task_dialog.ShowModal();
}

void ClouDownFrame::OnTimerTrigger(wxTimerEvent& event) {
  int count = list_ctrl_downloading->GetItemCount();
  for (int i = 0; i < count; ++i) {
    long long int* last_count = (long long int*)list_ctrl_downloading->GetItemData(i);
    Task* task = task_manager_.GetTask(i);
    long long int file_size = task->GetFileSize();
    long long int current_count = task->GetTotalByte();

    if (current_count >= file_size) {
      current_count = file_size;
      list_ctrl_downloading->SetItem(i, 0, _("已完成"));
    }
    wxString percent =
      wxString::Format(_("%.2f%%"), (double)current_count / file_size * 100);
    list_ctrl_downloading->SetItem(i, 3, percent);
    wxString speed =
      wxString::Format(_("%.2fKB/S"), (double)(current_count - *last_count) / 1024);
    list_ctrl_downloading->SetItem(i, 4, speed);
    *last_count = current_count;

    if (i == list_ctrl_downloading->GetSelectedItemCount()) {
      text_ctrl_info->Clear();
      string s;
      task->GetFilePathAndName(s);  // 完整的文件路径
      wxString file_path_and_name(s.c_str(), wxConvFile);
      text_ctrl_info->AppendText(_("文件名："));
      text_ctrl_info->AppendText(file_path_and_name);
      text_ctrl_info->AppendText(_("\n"));

      task->GetFullURL(s);
      wxString full_url(s.c_str(), wxConvFile);
      text_ctrl_info->AppendText(_("完整URL："));
      text_ctrl_info->AppendText(full_url);
      text_ctrl_info->AppendText(_("\n"));

      text_ctrl_info->AppendText(_("文件大小："));
      text_ctrl_info->AppendText(wxString::Format(_("%lld字节"), file_size));
      text_ctrl_info->AppendText(_("\n"));

      text_ctrl_info->AppendText(_("已完成："));
      text_ctrl_info->AppendText(percent);
      text_ctrl_info->AppendText(_("\n"));

      text_ctrl_info->AppendText(_("即时速度："));
      text_ctrl_info->AppendText(speed);
      text_ctrl_info->AppendText(_("\n"));

      task->GetReferer(s);
      wxString referer(s.c_str(), wxConvFile);
      text_ctrl_info->AppendText(_("引用页："));
      text_ctrl_info->AppendText(referer);
      text_ctrl_info->AppendText(_("\n"));
    }
  }
}
